# -*- coding:utf-8 -*-

from rest_framework.exceptions import APIException
from django.core.cache import cache
import requests
from Apps.System.models.corp import Corp
import logging

logger = logging.getLogger("django")


def tryGetToken(fun):
    def wrap(*code):
        try:
            count = 0
            result = fun(*code)

            # 如果返回的错误code不是0，并且重试次数大于三次，就报错
            if result["errcode"] != 0 and count < 3:

                # 获取应用token
                ApplicationToken = Chart()._getApplicationToken()
                logger.info(f"获取的应用token报文:{ApplicationToken}")

                application_token = ApplicationToken.get("access_token")
                logger.info(f"获取的应用token:{application_token}")

                cache.set("_ApplicationToken", application_token)

                # 获取通讯录token
                ContactsToken = Chart()._getContactsToken()
                logger.info(f"获取的通讯录token报文:{ContactsToken}")

                contacts_token = ContactsToken.get("access_token")
                logger.info(f"获取的通讯录token:{contacts_token}")

                cache.set("_ContactsToken", contacts_token)

                # 重新调用函数
                # 需要实例化，重新拿到放置的token
                new_chart = Chart()
                fun_name = getattr(new_chart, fun.__name__)
                result = fun_name()
                count += 1
                logger.info(f"当前重试次数:{count},")
            return result
        except:
            logger.error(f"企微token接口报错！！")
            raise APIException("企微token接口报错！！")

    return wrap


class Chart:

    def __init__(self):
        """
        {
        "errcode": 42001,
        "errmsg": "access_token expired, hint: [1652270722206731201436142], from ip: 112.65.0.83, more info at https://open.work.weixin.qq.com/devtool/query?e=42001",
        "department": [],
        "order": [],
        "is_leader_in_dept": [],
        "direct_leader": []
        }

        # self._ApplicationToken = "HHDQIT68im9ZqLPqhFTnVSY1Ht28fkaG6Z4xo3RdX0t1H3Grv850Ue3p-nTG6zKH8IOBHU7ThDwNCC7yPdo0Za1MGcaHBtG8hr68l__tX_qk6WXGQLPvoRAEZojuSqyoC5ZTUu00fZmdX0J9SUXsfoeD7iLDGEZWAWWm3jA8wU1niqvKpKIkLPFfkTjdZ5F9tV75X4bSHOe9fGbFN_O_xg"
        # self._CommunicationToken = "KsL6sHOuwLrGZxljm4uO2jLIm36WQL0T7UXxiWwrF2TcWNeea054WoX0YWyDzL8KSKnwaP9r9jCjNUCdo93-dFYG4d486JlpwMa0KSk-IiDOTXl2NQ3WOkiw1Ro8iLaqE-yOGX-ahNTwlzY1WtGJPEXKlPekn0WeAVwPipGa3EJOdiCnsVyuSSkLeHQ4vPR9akKWIVyiRPROUXoJMOKpxQ"

        """
        # 当前启用的企业
        company = Corp.objects.filter(enable='1').first()
        self._corp_id = company.corpid
        self._application_secret = company.application_secret
        self._contacts_secret = company.contacts_secret
        self._ApplicationToken = cache.get("_ApplicationToken")
        self._ContactsToken = cache.get("_ContactsToken")

    def _getApplicationToken(self):
        """
        企业ID    wwe9f6a4e657c8bb09
        应用Secret    cb0eiGwQYjNbRPXtSVKICGH8VYjizlwrZcLr3FbhuSo

        {"errcode":0,"errmsg":"ok","access_token":"MXhiY1UNgwkvXM5i0zRhbS1jmuXBFFVhJpPMNZJVQ4Rj-A3HNuYp5tiWqb5oKkyV3Agb9008zU-PMLNYZCZwm92057jH5oLeL6egwqcW2PbwCrKO04hx3DIoQ_PLnGahydaGikRHYRCtCT9JGp-vqfkTl6Q0hIbIZawIbKeb70PZT26GMGnycboyUYKfP7QHq-5XX99Mg428OeZLhVBDpw","expires_in":7200}

        """
        # params = {"corpid": self._corpid, "corpsecret": "cb0eiGwQYjNbRPXtSVKICGH8VYjizlwrZcLr3FbhuSo"}
        params = {"corpid": self._corp_id, "corpsecret": self._application_secret}
        url = 'https://qyapi.weixin.qq.com/cgi-bin/gettoken'
        response = requests.get(url=url, params=params)
        return response.json()

    def _getContactsToken(self):
        """
        通讯录同步
        可通过API接口或第三方应用同步通讯录
        通讯录同步Secret   OcCMM9z-oNb5jm55UHPuvTeftqVCkD1DXQXD6V-zHAk

        {"errcode":0,"errmsg":"ok","access_token":"MXhiY1UNgwkvXM5i0zRhbS1jmuXBFFVhJpPMNZJVQ4SZMNR52XZvkWoyGOQZmKmP1ZgllaK2hAPyY4YEtQASwmM_T0Diupd5dozT3hXR_l4bClB7c3C7FPxaQNjqe-1Mo-TYAvqvGrRbs1FiMwBs8tnRvheJzdYGYQUyq6tz-_j81em53mdsS-QPxOSPqiFHJz5Qrgu1Fe6-n4IghLYoBg","expires_in":7200}

        """

        # params = {"corpid": self._corpid, "corpsecret": "OcCMM9z-oNb5jm55UHPuvTeftqVCkD1DXQXD6V-zHAk"}
        params = {"corpid": self._corp_id, "corpsecret": self._contacts_secret}
        url = 'https://qyapi.weixin.qq.com/cgi-bin/gettoken'

        response = requests.get(url=url, params=params)

        """
            数据同步
            可将企业使用的 Microsoft Active Directory 与 Exchange 的帐号、邮箱和日历数据统一迁移至企业微信并持续同步。
         """
        return response.json()

    # 获取登陆二维码（已弃用）改为前端直接生成
    def loginCode(self):
        """

        appid	        是	    企业微信的CorpID，在企业微信管理端查看
        agentid	        是	    授权方的网页应用ID，在具体的网页应用中查看
        redirect_uri	是	    重定向地址，需要进行UrlEncode
        state	        否	    用于保持请求和回调的状态，授权请求后原样带回给企业。该参数可用于防止csrf攻击（跨站请求伪造攻击），建议企业带上该参数，可设置为简单的随机数加session进行校验
        lang	        否	    自定义语言，支持zh、en；lang为空则从Headers读取Accept-Language，默认值为zh

        假定当前
        企业CorpID：wxCorpId
        开启授权登录的应用ID：1000000
        登录跳转链接：http://api.3dept.com
        state设置为：weblogin@gyoss9

        需要配置的授权回调域为：api.3dept.com

        根据URL规范，将上述参数分别进行UrlEncode，得到拼接的OAuth2链接为：
        https://open.work.weixin.qq.com/wwopen/sso/qrConnect?appid=wxCorpId&agentid=1000000&redirect_uri=http%3A%2F%2Fapi.3dept.com&state=web_login%40gyoss9

        :return: 返回一个二维码的HTML页面，需要嵌套到登录网页中
        """
        params = {"appid": self._corp_id, "agentid": 1000002, "redirect_uri": "https://xielei-yy.com",
                  "code": "2345", "state": "", "lang": ""}
        url = "https://open.work.weixin.qq.com/wwopen/sso/qrConnect?appid=wwe9f6a4e657c8bb09&agentid=1000002&redirect_uri=https://xielei-yy.com&code=sadad&state=scscasd"

        url = "https://open.work.weixin.qq.com/wwopen/sso/qrConnect"
        response = requests.get(url=url, params=params)
        return response.json()

    # 企微扫码登陆，回调获取当前登陆人的信息
    @tryGetToken
    def getLoginUserByCode(self, code):
        """
        企微登陆跳转，code回调用户信息
        :param code:
        :return:
                {
                   "errcode": 0,
                   "errmsg": "ok",
                   "UserId":"USERID"
                }
        """
        access_token = self._ApplicationToken
        params = {"code": code, "access_token": access_token}
        url = "https://qyapi.weixin.qq.com/cgi-bin/user/getuserinfo"

        response = requests.get(url=url, params=params)
        return response.json()

    # 通过回调获取的userid，查询当前企微用户的信息，或更新数据时，同步系统数据
    @tryGetToken
    def getUser(self, userid):
        """
        读取成员
        """
        print(userid)
        access_token = self._ContactsToken
        print(access_token)
        params = {"userid": userid, "access_token": access_token}
        url = "https://qyapi.weixin.qq.com/cgi-bin/user/get"

        response = requests.get(url=url, params=params)
        print(response.text)
        return response.json()

    @tryGetToken
    def getSimpleList(self):
        """
        获取部门成员
        :return:
        {"errcode":0,"errmsg":"ok","userlist":[{"name":"SmallStrong","department":[1],"userid":"smallstrong"},
        {"name":"嗯哼","department":[1],"userid":"ha"},{"name":"谢磊","department":[1],"userid":"XieLei"}]}

        {"errcode":0,"errmsg":"ok","userlist":[{"name":"SmallStrong","department":[1],"userid":"smallstrong"},
        {"name":"嗯哼","department":[2],"userid":"ha"},{"name":"谢磊","department":[1],"userid":"XieLei"}]}
        """
        access_token = self._ContactsToken
        params = {"department_id": "1", "fetch_child": "1", "access_token": access_token}
        url = "https://qyapi.weixin.qq.com/cgi-bin/user/simplelist"

        response = requests.get(url=url, params=params)
        print(response.text)
        return response.json()

    def getList(self):
        """
        获取部门成员详情
        """
        access_token = self._ContactsToken
        params = {"department_id": "1", "fetch_child": "1", "access_token": access_token}
        url = "https://qyapi.weixin.qq.com/cgi-bin/user/list"

        response = requests.get(url=url, params=params)
        # pprint(response.text)
        return response.json()

    @tryGetToken
    def sendText(self):
        """
        发送应用消息
        :return:
        """
        data = {
            "touser": "@all",
            "toparty": "",
            "totag": "",
            "msgtype": "text",
            "agentid": 1000002,
            "text": {
                "content": "哈哈哈哈 \n测试一下<a href = '#'>这是H1</a>"
            },
            "safe": 0,
            "enable_id_trans": 0,
            "enable_duplicate_check": 0,
            "duplicate_check_interval": 1800
        }
        access_token = self._ApplicationToken

        url = f"https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token={access_token}"

        response = requests.post(url=url, json=data)
        # {"errcode": 40014, "errmsg": "invalid access_token"}
        return response.json()


if __name__ == '__main__':
    c = Chart()
    c.sendText()
    # print(c.getUser("XieLei"))
